<?php
/**
 * User: AK.
 * Date: 2019/7/17
 * 完成用户登录、注册、验证token等功能
 */
class Supplybuy extends CI_Model{

	

   //新增供求数据
   public function add_app_supply($data)
   {
		//判断操作op:add edit  del
		$op = $data['op'];
		$id = $data['id'];
		
		if(isset($data)){
			//判断base64图片转换
			
			if($data['img']<>""){
				$imgurl = $this->base64_image_content($data['img'],'/static/images/upload');
				if($imgurl){
					$data['img'] = $this->config->item('base_url').$imgurl;
				}
			}	
			if($op == "add"){
				unset($data['op']);
				unset($data['id']);
				$this->db->insert('app_supply',$data);
				return true;		
			}elseif($op == "edit"){
				unset($data['op']);
				unset($data['id']);
				if ($id<1) return false; 
				$this->db->where("id",$id);
				$this->db->update('app_supply',$data);				
				return true;		
			}elseif($op == "del"){
				if ($id<1) return false; 
				$this->db->where("id",$id);
				$this->db->delete('app_supply');
				return true;		
			}
		}
		return false;
   }
      

	/*  base64格式编码转换为图片并保存对应文件夹 */
	public function base64_image_content($base64_image_content,$path){
		//匹配出图片的格式
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
			$myapppath = dirname(APPPATH);

			$type = $result[2];
			$new_file = $path."/".date('Ymd',time())."/";
	
			if(!file_exists($myapppath.$new_file)){
				//检查是否有该文件夹，如果没有就创建，并给予最高权限

				mkdir($myapppath.$new_file);
			}
	
			$new_file = $new_file.time().".{$type}";

			if (file_put_contents($myapppath.$new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
				return $new_file;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
   //获取供求数据
   //data['type']  data['kw']
   public function get_app_supply($data)
   {
	   if(!isset($data['type'])){
	   		return false;
	   }
	   
       $this->db->select("id,type,img,kname,unit,price,nums,content,mobile,inputdate,state");
       if(isset($data['state'])){
		   $this->db->where("state",$data['state']);
	   }else{
		   $this->db->where("state",1);
	   }
	   if(isset($data['uid'])){
	   	$this->db->where("uid",$data['uid']);
	   }	   
	   if(isset($data['kw'])){
			$this->db->like("kname",$data['kw']);
	   }
       $this->db->where("type",$data['type']);
       $this->db->from('app_supply');
       $query = $this->db->get();
       return $query->result_array();
   }


}